<!-- 参考地址 -->
<!-- https://devpress.csdn.net/viewdesign/64376a2f986c660f3cf939ef.html?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Eactivity-5-125005672-blog-118551128.235%5Ev29%5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Eactivity-5-125005672-blog-118551128.235%5Ev29%5Epc_relevant_default_base3&utm_relevant_index=10 -->
<!-- 
使用说明：

1.引入组件
import MyDatePicker from "./MyDatePicker.vue";

2.注入组件
components: {
    MyDatePicker,
},

3.标签使用
<MyDatePicker 
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    v-model="dateValue"
    :value="dateValue"
/>

v-model 配合 this.$emit("input", item.value);  回显切双向绑定值
:value 只是回显


 -->
<template>
  <div ref="dateMain" style="width: 300px">
    <el-input
      v-model="dateValue"
      :placeholder="placeholder"
      :clearable="clearable"
      :disabled="disabled"
      :readonly="readonly"
    >
      <i
        slot="prefix"
        class="el-input__icon el-icon-date"
        @click="openDateDialog($event)"
      ></i>
      <i
        v-if="readonly"
        slot="suffix"
        class="el-input__icon el-icon-circle-close"
        @click="clearDateValue($event)"
      ></i>
    </el-input>
    <div class="calendar-box" :id="dateId" v-show="dateDialog">
      <div class="calendar-wrapper">
        <div
          v-if="quickOptions && quickOptions.length > 0"
          style="padding-top: 10px"
        >
          <el-tag
            v-for="item in quickOptions"
            :key="item.level"
            size="small"
            style="margin-right: 20px"
            @click="changValue(item)"
            >{{ item.level }}</el-tag
          >
        </div>
        <div class="calendar-toolbar">
          <button
            type="button"
            aria-label="前一年"
            class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left"
            @click="prevYear"
          ></button>
          <button
            type="button"
            aria-label="上个月"
            @click="prevMonth"
            class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-arrow-left"
          ></button>
          <div class="current">{{ currentDateStr }}</div>
          <button
            type="button"
            aria-label="下个月"
            @click="nextMonth"
            class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-arrow-right"
          ></button>
          <button
            type="button"
            aria-label="后一年"
            @click="nextYear"
            class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right"
          ></button>
        </div>
        <div class="calendar-week">
          <div
            class="week-item calendar-border"
            v-for="item of weekList"
            :key="item"
          >
            {{ item }}
          </div>
        </div>
        <div class="calendar-inner">
          <div
            class="calendar-item calendar-border"
            v-for="(item, index) of calendarList"
            :key="index"
            :class="{
              'calendar-item': true,
              'calendar-border': true,
              'calendar-item-hover': !item.disable,
              'calendar-item-disabled': item.disable,
              'calendar-item-checked':
                dayChecked && dayChecked.value == item.value,
            }"
            @click="handleClickDay(item)"
          >
            {{ item.date }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

export default {
  name: "MyDatePicker",
  props: {
    // 传入日期参数
    value: {
      type: String,
      default: "",
    },
    // 文本框默认提示语
    placeholder: {
      type: String,
      default: "",
    },
    // 文本框清理按钮
    clearable: {
      type: Boolean,
      default: true,
    },
    // 文本框禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 文本框只读
    readonly: {
      type: Boolean,
      default: true,
    },
    /**
     * 自定义快捷选项
     * [
     *  {level: '1', value:'最近一个月'},
     *  {level: '2', value:'最近一周'},
     * ]
     */
    quickOptions: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      dateId: new Date().getTime() + "_id",
      dateValue: this.value,
      dateDialog: false,
      showYearMonth: {}, // 显示的年月
      calendarList: [], // 用于遍历显示
      shareDate: new Date(), // 享元模式，用来做 日期数据转换 优化
      dayChecked: {}, // 当前选择的天
      weekList: ["一", "二", "三", "四", "五", "六", "日"], // 周
    };
  },
  created() {
    this.initDataFun(); // 初始化数据
  },
  mounted() {
    document.addEventListener("click", this.bodyCloseMenus);
  },
  computed: {
    // 显示当前时间
    currentDateStr() {
      let { year, month } = this.showYearMonth;
      return `${year}年${this.pad(month + 1)}月`;
    },
  },
  beforeDestroy() {
    document.removeEventListener("click", this.bodyCloseMenus);
  },
  watch: {
    value: {
      handler(val) {
        if (val !== this.dateValue) {
          this.dateValue = val === null ? "" : val;
        }
      },
      immediate: true,
    },
  },
  methods: {
    bodyCloseMenus(e) {
      let self = this;
      if (this.$refs.dateMain && !this.$refs.dateMain.contains(e.target)) {
        if (self.dateDialog == true) {
          self.dateDialog = false;
        }
      }
    },
    //#region 计算日历数据
    // 初始化数据
    initDataFun() {
      // 初始化当前时间
      this.setCurrentYearMonth(); // 设置日历显示的日期（年-月）
      this.createCalendar(); // 创建当前月对应日历的日期数据
      this.getCurrentDay(); // 获取今天
    },
    // 设置日历显示的日期（年-月）
    setCurrentYearMonth(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.showYearMonth = {
        year,
        month,
        date,
      };
    },
    getCurrentDay(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.dayChecked = {
        year,
        month,
        date,
        value: this.stringify(year, month, date),
        disable: false,
      };
    },
    // 创建当前月对应日历的日期数据
    createCalendar() {
      // 一天有多少毫秒
      const oneDayMS = 24 * 60 * 60 * 1000;
      let list = [];
      let { year, month } = this.showYearMonth;
      // #region
      // ---------------仅仅只算某月的天---------------
      //   // 当前月，第一天和最后一天的毫秒数
      //   let begin = new Date(year, month, 1).getTime();
      //   let end = new Date(year, month + 1, 0).getTime();
      // ---------------计算某月前后需要填补的天---------------
      // 当前月份第一天是星期几, 0-6
      let firstDay = this.getFirstDayByMonths(year, month);
      // 填充多少天，因为我将星期日放到最后了，所以需要另外调整下
      let prefixDaysLen = firstDay === 0 ? 6 : firstDay - 1;
      // 向前移动之后的毫秒数
      let begin = new Date(year, month, 1).getTime() - oneDayMS * prefixDaysLen;
      // 当前月份最后一天是星期几, 0-6
      let lastDay = this.getLastDayByMonth(year, month);
      // 填充多少天，因为我将星期日放到最后了，所以需要另外调整下
      let suffixDaysLen = lastDay === 0 ? 0 : 7 - lastDay;
      // 向后移动之后的毫秒数
      let end =
        new Date(year, month + 1, 0).getTime() + oneDayMS * suffixDaysLen;
      // // 计算左侧时间段的循环数
      // let rowNum = Math.ceil((end - begin) / oneDayMS / 7);
      // let newPeriod = [];
      // for (let i = 0; i < rowNum; i++) {
      //   newPeriod.push({});
      // }
      // #endregion
      // 填充天
      while (begin <= end) {
        // 享元模式，避免重复 new Date
        this.shareDate.setTime(begin);
        let year = this.shareDate.getFullYear();
        let curMonth = this.shareDate.getMonth();
        let date = this.shareDate.getDate();
        list.push({
          year: year,
          month: curMonth + 1, // 月是从0开始的
          date: date,
          value: this.stringify(year, curMonth, date),
          disable: curMonth !== month,
        });
        begin += oneDayMS;
      }
      this.calendarList = list;
    },
    // 格式化时间
    stringify(year, month, date) {
      let str = [year, this.pad(month + 1), this.pad(date)].join("-");
      return str;
    },
    // 对小于 10 的数字，前面补 0
    pad(str) {
      return str < 10 ? `0${str}` : str;
    },
    // 点击上一年
    prevYear() {
      this.showYearMonth.year--;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 点击下一年
    nextYear() {
      this.showYearMonth.year++;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 点击上一月
    prevMonth() {
      this.showYearMonth.month--;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 点击下一月
    nextMonth() {
      this.showYearMonth.month++;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 重算：显示的某年某月
    recalculateYearMonth() {
      let { year, month, date } = this.showYearMonth;
      let maxDate = this.getDaysByMonth(year, month);
      // 预防其他月跳转到2月，2月最多只有29天，没有30-31
      date = Math.min(maxDate, date);
      let instance = new Date(year, month, date);
      this.setCurrentYearMonth(instance);
    },
    // 判断当前月有多少天
    getDaysByMonth(year, month) {
      return new Date(year, month + 1, 0).getDate();
    },
    // 当前月的第一天是星期几
    getFirstDayByMonths(year, month) {
      return new Date(year, month, 1).getDay();
    },
    // 当前月的最后一天是星期几
    getLastDayByMonth(year, month) {
      return new Date(year, month + 1, 0).getDay();
    },
    // #endregion 计算日历数据
    // 操作：点击了某天
    handleClickDay(item) {
      if (!item || item.disable) return;
      //console.log(item);
      this.dayChecked = item;
      this.dateValue = item.value;
      this.dateDialog = false;
      this.$emit("input", item.value);
    },
    // 点击快捷操作
    changValue(item) {
      this.dateValue = item.value;
      this.dateDialog = false;
      this.$emit("input", item.value);
    },
    // 只读时 清理内容
    clearDateValue() {
      this.dateValue = "";
      this.dateDialog = false;
      this.$emit("input", "");
    },
    // 打开日期弹窗
    openDateDialog(e) {
      if (!this.disabled) {
        this.dateDialog = !this.dateDialog;
        var x = e.pageX;
        var y = e.pageY + 30;
        // var clientWidth = document.documentElement.clientWidth;
        var clientHeight = document.documentElement.clientHeight;
        // 处理弹窗溢出出现滚动条
        var ph = y + 300;
        if (ph >= clientHeight) {
          y = e.pageY - 290;
        }
        if (this.dateDialog) {
          document.getElementById(this.dateId).style.top = y + "px";
          document.getElementById(this.dateId).style.left = x + "px";
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
/**
  less
*/
@calendarWidth: 260px; // 90 * 7 + 7 * 1
@colSize: 36px;
.calendar-box {
  width: auto;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  z-index: 999;
  background: #fff;
  top: 0;
  .calendar-wrapper {
    padding: 14px 18px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    font-size: 12px;
    .calendar-toolbar {
      width: @calendarWidth;
      height: @colSize;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .prev,
      .next,
      .current {
        cursor: pointer;
        &:hover {
          color: #438bef;
        }
      }
    }
    .calendar-week {
      width: @calendarWidth;
      //   border-bottom: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      .week-item {
        width: @colSize;
        height: @colSize;
        border-top: 1px solid #eee;
      }
    }
    .calendar-inner {
      width: @calendarWidth;
      //   border-left: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      .calendar-item {
        width: @colSize;
        height: @colSize;
        color: #606266;
      }
      .calendar-item-hover {
        cursor: pointer;
        &:hover {
          color: #438bef;
          // background-color: #438bef;
        }
      }
      .calendar-item-disabled {
        color: #acacac;
        cursor: not-allowed;
      }
      .calendar-item-checked {
        color: #438bef;
        // background-color: #438bef;
      }
    }
    .calendar-border {
      display: flex;
      justify-content: center;
      align-items: center;
      //   border-bottom: 1px solid #eee;
      //   border-right: 1px solid #eee;
    }
  }
}
</style>
